"""
集成使用示例
展示如何同时使用RAG和高德地图功能
"""

import sys
import os
import logging

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from tools.rag_tool import RAGTool
from tools.amap_tool import AmapTool, TravelMode
from utils.config import Config

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

class TravelAssistant:
    """旅游助手类，集成RAG和地图功能"""
    
    def __init__(self):
        """初始化旅游助手"""
        self.rag_tool = None
        self.amap_tool = None
        
        # 初始化RAG工具
        try:
            Config.validate_config()
            self.rag_tool = RAGTool()
            logger.info("✓ RAG工具初始化成功")
        except Exception as e:
            logger.warning(f"RAG工具初始化失败: {str(e)}")
        
        # 初始化高德地图工具
        try:
            Config.validate_amap_config()
            self.amap_tool = AmapTool()
            logger.info("✓ 高德地图工具初始化成功")
        except Exception as e:
            logger.warning(f"高德地图工具初始化失败: {str(e)}")
    
    def answer_travel_question(self, question: str) -> str:
        """回答旅游相关问题"""
        if not self.rag_tool:
            return "抱歉，RAG功能暂不可用，请检查配置。"
        
        try:
            result = self.rag_tool.answer_question(question)
            return result.get('answer', '无法回答该问题')
        except Exception as e:
            return f"回答问题时出错: {str(e)}"
    
    def plan_route(self, origin: str, destination: str, mode: str, city: str = None) -> str:
        """规划路线"""
        if not self.amap_tool:
            return "抱歉，地图功能暂不可用，请检查配置。"
        
        try:
            # 转换出行方式字符串为枚举
            mode_map = {
                'walking': TravelMode.WALKING,
                'bicycling': TravelMode.BICYCLING,
                'transit': TravelMode.TRANSIT,
                'driving': TravelMode.DRIVING
            }
            
            travel_mode = mode_map.get(mode.lower(), TravelMode.DRIVING)
            result = self.amap_tool.plan_route(origin, destination, travel_mode, city)
            
            if 'error' in result:
                return f"路线规划失败: {result['error']}"
            
            return self.amap_tool.get_route_summary(result)
        except Exception as e:
            return f"路线规划时出错: {str(e)}"
    
    def get_travel_suggestion(self, destination: str, city: str = None) -> str:
        """获取旅游建议（结合RAG和地图功能）"""
        suggestions = []
        
        # 使用RAG获取目的地信息
        if self.rag_tool:
            rag_question = f"{destination}有哪些旅游景点和特色？"
            rag_answer = self.answer_travel_question(rag_question)
            suggestions.append(f"📚 目的地信息：\n{rag_answer}")
        
        # 使用地图功能获取交通信息
        if self.amap_tool and city:
            try:
                # 获取目的地坐标
                geocode_result = self.amap_tool.geocode_address(destination, city)
                if 'error' not in geocode_result:
                    suggestions.append(f"📍 位置信息：\n{geocode_result['address']}")
                    suggestions.append(f"坐标：{geocode_result['longitude']}, {geocode_result['latitude']}")
            except Exception as e:
                suggestions.append(f"获取位置信息失败: {str(e)}")
        
        return "\n\n".join(suggestions) if suggestions else "无法获取旅游建议"

def demo_integrated_usage():
    """演示集成使用"""
    logger.info("=" * 60)
    logger.info("旅游助手集成功能演示")
    logger.info("=" * 60)
    
    # 初始化旅游助手
    assistant = TravelAssistant()
    
    # 演示RAG功能
    logger.info("\n" + "=" * 50)
    logger.info("RAG功能演示")
    logger.info("=" * 50)
    
    rag_questions = [
        "成都有哪些著名的旅游景点？",
        "成都的特色美食有哪些？",
        "去成都旅游有什么建议？"
    ]
    
    for question in rag_questions:
        logger.info(f"\n问题: {question}")
        logger.info("-" * 40)
        answer = assistant.answer_travel_question(question)
        logger.info(f"回答: {answer[:200]}...")
    
    # 演示地图功能
    logger.info("\n" + "=" * 50)
    logger.info("地图功能演示")
    logger.info("=" * 50)
    
    route_requests = [
        {
            "origin": "天府广场",
            "destination": "春熙路",
            "mode": "walking",
            "city": "成都"
        },
        {
            "origin": "天府广场",
            "destination": "宽窄巷子",
            "mode": "bicycling",
            "city": "成都"
        }
    ]
    
    for request in route_requests:
        logger.info(f"\n路线规划: {request['origin']} -> {request['destination']} ({request['mode']})")
        logger.info("-" * 40)
        route_info = assistant.plan_route(
            request['origin'],
            request['destination'],
            request['mode'],
            request['city']
        )
        logger.info(route_info)
    
    # 演示集成功能
    logger.info("\n" + "=" * 50)
    logger.info("集成功能演示")
    logger.info("=" * 50)
    
    destinations = ["春熙路", "宽窄巷子", "都江堰"]
    
    for destination in destinations:
        logger.info(f"\n{destination} 旅游建议:")
        logger.info("-" * 40)
        suggestion = assistant.get_travel_suggestion(destination, "成都")
        logger.info(suggestion)

def main():
    """主函数"""
    logger.info("旅游助手集成使用示例")
    logger.info("=" * 60)
    
    try:
        demo_integrated_usage()
        
        logger.info("\n" + "=" * 60)
        logger.info("集成使用示例演示完成！")
        logger.info("=" * 60)
        
    except Exception as e:
        logger.error(f"示例运行出错: {str(e)}")

if __name__ == "__main__":
    main()
